package com.band.manager.shiro.reaml;

import com.band.manager.entity.Role;
import com.band.manager.entity.User;
import com.band.manager.entity.UserExample;
import com.band.manager.mapper.UserMapper;
import com.band.manager.mapper.myUserRoleMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;

public class myReaml extends AuthorizingRealm {

    @Resource
    myUserRoleMapper myUserRoleMapper;

    @Resource
    UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User)principalCollection.getPrimaryPrincipal();
        //查出改用户对应的所有角色
        List<Role> roles = myUserRoleMapper.listRolesByPrimaryKey(user.getId());
        //添加到授权信息中
        roles.forEach(role -> {
            info.addRole(role.getName());
        });

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auToken) throws AuthenticationException {
//        传入的token是用户填写的表单 如账户密码
        UsernamePasswordToken token = (UsernamePasswordToken) auToken;
        //这里通过用户传进来的账户到数据库中查找相应的账户信息包括正确的密码
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(token.getUsername());
        User user = userMapper.selectByExample(example).get(0);
        //返回认证信息，包括：user（包含账户所有信息），密码，reaml的名字（因为可能会存在多个reaml）
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
